package com.ruoyi.weixin.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.weixin.config.WxMaConfiguration;
import com.ruoyi.weixin.domain.WxUserDto;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author wc
 */
@Slf4j
@Service
public class WxUserService {

    //微信app id
    @Value("${wechat.miniapp.configs[0].appid}")
    private String appid;

    /**
     * 获取openid
     *
     * @param param
     * @return
     */
    public String getOpenId(Map<String, Object> param) {
        String code = param.get("code").toString();

        if (StringUtils.isBlank(code)) {
            return null;
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
//            log.info(session.getSessionKey());
//            log.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            return session.getOpenid();
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 获取用户信息接口
     *
     * @param dto
     * @return
     */
    public WxMaUserInfo getInfo(WxUserDto dto) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(dto.getSessionKey(), dto.getRawData(), dto.getSessionKey())) {
            throw new ServiceException("user check failed");
        }

        // 解密用户信息
        return wxService.getUserService().getUserInfo(dto.getSessionKey(), dto.getEncryptedData(), dto.getIv());
    }

    /**
     * 获取用户手机号
     *
     * @param dto
     * @return
     */
    public WxMaPhoneNumberInfo getPhone(WxUserDto dto) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(dto.getSessionKey(), dto.getRawData(), dto.getSessionKey())) {
            throw new ServiceException("user check failed");
        }

        // 解密用户信息
        return wxService.getUserService().getPhoneNoInfo(dto.getSessionKey(), dto.getEncryptedData(), dto.getIv());
    }
}
